import 'dart:async';

import 'package:collection/collection.dart';
import 'package:flutter_axrjc/datasource/network/api/LightApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/CheckLogBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/EventBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/LightBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/main.dart';
import 'package:flutter_axrjc/util/Util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'state.dart';

class LightDetailLogic extends GetxController {
  final LightDetailState state = LightDetailState();
  late LightBean bean;
  var refreshController = RefreshController(initialRefresh: true);

  StreamSubscription<EventBean>? listener;
  @override
  void onInit() {
    super.onInit();
    listener = eventBus.on<EventBean>().listen((event) {
      if (event.type == EventType.refreshLightImge) {
        getImages("${bean.fixtureId}");
      }
    });
    bean = Get.arguments as LightBean;
  }

  Future<void> getImages(String id) async {
    state.imgList.clear();
    state.imgList.addAll(await LightApi.getImage(id));
  }

  Future<void> getLog() async {
    state.list.clear();
    getImages("${bean.fixtureId}");

    try {
      List<CheckLogBean> list =
          await LightApi.getLogListById(fixtureId: "${bean.fixtureId}");
      state.list.addAll(groupBy(
          list,
          (p0) => Util.date2String(
              Util.string2Date("${p0.detectionStartTime}")!)).entries);
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      print(e);
    }

    refreshController.refreshCompleted();
  }

  @override
  void onClose() {
    super.onClose();
    listener?.cancel();
  }
}
